#include "List.h"
ListNode* BuyListNode(LTDataType x){
    ListNode* newnode=(ListNode*)malloc(sizeof(LTDataType));
    newnode->data=x;
    newnode->next=NULL;
    newnode->prev=NULL;
};
ListNode * ListInit(){
    ListNode* phead= BuyListNode(0);
    phead->next=phead;
    phead->prev=phead;
    return phead;
}
void ListDestory(ListNode* phead){
    assert(phead);
    ListNode* cur=phead->next;
    while (cur!=phead){
        ListNode* next=cur->next;
        free(cur);//一个一个的释放
        cur=cur->next;//释放完后值转为下一个节点，继续释放
    }
//    最后释放头结点，并赋值为空
    free(phead);
    phead=NULL;
}
void ListPushBack(ListNode* phead,LTDataType x){
    assert(phead);
    ListNode* tail=phead->prev;
    ListNode* newnode= BuyListNode(x);
//    tail与新的值连接
    tail->next=newnode;
    newnode->prev=tail;
//    新的值与头相链接
    newnode->next=phead;
    phead->prev=newnode;
}
void ListNodePushFront(ListNode* phead,LTDataType x){
    assert(phead);
    ListNode* first=phead->next;
    ListNode* newnode= BuyListNode(x);
    //phead newnode first
    phead->next= newnode;
    newnode->prev=phead;
    first->prev=newnode;
    newnode->next=first;
}
void Print(ListNode* phead){
    ListNode* cur=phead->next;
    while (cur!=phead){
        printf("%d ",cur->data);
        cur=cur->next;
    }
    printf("\n");
}
void ListNodePopBack(ListNode* phead){
    assert(phead);
    assert(phead->next!=phead);
    ListNode* tail=phead->prev;
    ListNode* prev=tail->prev;
//    phead prev
    phead->prev=prev;
    prev->next= phead;

    free(tail);
    tail=NULL;
}
void ListNodePopFront(ListNode* phead){
    assert(phead);
    assert(phead->next!=phead);
    ListNode*first=phead->next;
    ListNode* second=first->next;
//    phead first second

    phead->next=second;
    second->prev=phead;
    free(first);
    first=NULL;
}
ListNode * ListFind(ListNode* phead, LTDataType x){
    assert(phead);
    ListNode* cur=phead->next;
    while (cur!=phead){
        if (cur->data==x){
            return cur;
        }
        cur=cur->next;
    }
    return NULL;
}
void LisrInsert(ListNode* pos,LTDataType x){
    assert(pos);
    ListNode * prev=pos->prev;
    ListNode * newnode= BuyListNode(x);
//    prev newnode pos
    prev->next=newnode;
    newnode->prev=prev;
    newnode->next=pos;
    pos->prev=newnode;
}
void ListErase(ListNode* pos){
    assert(pos);
    ListNode* prev=pos->prev;
    ListNode* next=pos->next;
    prev->next=next;
    next->prev=prev;
    free(pos);
}
//是否为空，assert
bool ListEmpty(ListNode* phead){
    assert(phead);
    return phead->next == phead;
}
//长度，直接遍历，计数
int ListSize (ListNode* phead){
    assert(phead);
    int count =0;
    ListNode* cur = phead->next; // 从第一个节点开始
    while (cur != phead) {       // 遍历到回到 phead 结束
        count++;
        cur = cur->next;
    }
    return count;
}
